const baseUrl="http://127.0.0.1:8080"

// 同时并发请求的次数
let ajaxTimes = 0

export const getBaseUrl = () => {
  return baseUrl
}

export const getWxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      timeout: 5000,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '获取用户信息',
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// Promise形式的 小程序微信支付封装
export const requestPay = (pay) => {
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      ...pay,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export const requestUtil=(params) => {
  // 判断url中是否带有 /my/ 请求的是私有的路径 带上header token
  let header = {...params.header}
  if(params.url.includes('/my')) {
    header['token'] = wx.getStorageSync('token')
  }

  ajaxTimes++
  wx.showLoading({
    title: '加载中...',
    mask: true
  })

  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      header,
      url: baseUrl+params.url,
      success: (result) => {
        resolve(result.data)
      },
      fail: (err) => {
        reject(result.data)
      },
      complete:() => {
        ajaxTimes--
        if (ajaxTimes == 0) {
          wx.hideLoading()
        }
      }
    })
  })
}